# -*- coding: utf-8 -*-
import easytrader

from dtrader.broker import BaseBroker
from dtrader.order.ashare import AshareOrder
from dtrader.portfolio.position import Position


class XueqiuBroker(BaseBroker):

    def __init__(self,user,password,portfolio_code,portfolio_market):
        """
        初始化用户名密码，可以从数据库读取
        """
        self.__broker_handler = easytrader.use("xq")
        self.__broker_handler.prepare(user=user, password=password,portfolio_code=portfolio_code,portfolio_market=portfolio_market)

    def create_market_order(self,ticker,action,quantity):
        """
        不支持市价单
        :param ticker:
        :param action:
        :param quantity:
        :return:
        """
        return None

    def create_limit_order(self,ticker,action,quantity,limit_price):

        if quantity >= 100:
            #@TODO quantity 取整
            return AshareOrder(ticker,action,limit_price,quantity)
        else:
            return None

    def submit_order(self,order):
        if not isinstance(order,AshareOrder):
            return None
        self.__user_handler.keepalive()

        if order.action == "BOT":
            self.__user_handler.buy(order.ticker, price = order.price, amount= order.quantity)
        else:
            self.__user_handler.sell(order.ticker, price=order.price, amount= order.quantity)

    def get_positions_from_broker(self):
        self.__user_handler.keepalive()
        return []






